package com.gj.demojuc.chap02;

import java.util.concurrent.locks.ReentrantLock;

class Ticket{
    private int number=50;
    private ReentrantLock lock = new ReentrantLock(true);
    public void sale(){
        lock.lock();
        if (number <= 0){
            System.out.println("票已售罄");
            lock.unlock();
            return;
        }
        try {
            System.out.println(Thread.currentThread().getName() + "开始售票共有"+number);
            Thread.sleep(200);
            number--;
            System.out.println(Thread.currentThread().getName() + "卖出一张剩余"+number);
            //检查余票
            check();
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }
    /**
     * 为了测试reentrantlock锁是可重入的，添加检查余票方法
     */
    public void check(){
        lock.lock();
        System.out.println("检查余票");
        lock.unlock();
    }
}

public class ReentrantlockDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{
            for (int i = 0; i < 51; i++) {
                ticket.sale();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 51; i++) {
                ticket.sale();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 51; i++) {
                ticket.sale();
            }
        },"C").start();
    }
}
